<template>
	<view class="doctor-container">
		<scroll-view class="scroll-view_H" scroll-y="true">
			<view class="top flex" v-if="registerType==1">
				<view class="alldoctor flex flex-column align-center justify-center">
					<text class="color-main f-s-28">全部</text>
					<text class="color-main f-s-28">医生</text>
				</view>
				<view style="width: calc(100% - 100rpx);">
					<scroll-view style="width: 100%;white-space: nowrap;" scroll-x="true">
						<view class="flex">
							<view :class="['date-item',activeIndex==index?'avtive':'']"
								v-for="(item, index) in dateList" :key="index" @click="viewDoctr(item,index)">
								<view style="width: 120rpx;height: 100%;"
									class="flex flex-column justify-around align-center">
									<text class="week">周{{item.reservationWeek}}</text>
									<text class="day">{{item.day}}</text>
									<text class="hao">
										<span style="color: #4D8EFF;" v-if="item.isReservation==1">有号</span>
										<span v-else>无号</span></text>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
			<view class="registra-date" v-if="doctorList.length>0">
				<view class="item flex flex-column" v-for="(item,index) in doctorList" :key="index"
					@click="showDetail(item)">
					<!-- <text class="f-s-28 color-999">普通号</text> -->
					<view class="item-bot flex">
						<!-- <img class="avatar"
							:src="item.doctor_img!=null?item.doctor_img:require('@/static/images/homeIndex/avator-doctor.png')"
							alt=""> -->
						<u--image width="60" height="60"
							:src="item.doctor_img ? item.doctor_img : require('@/static/images/homeIndex/avator-doctor.png')"
							shape="circle"></u--image>
						<view class="flex flex-column" style="flex: 3;">
							<text class="f-s-30 m-l-24 color-323232">{{item.xm}} {{item.ghlb}}</text>
							<text
								class="f-s-28 text2hang m-l-24 color-999 m-t-10">{{item.article_title ? item.article_title : '暂无简介'}}</text>
						</view>
						<!-- <view class="flex align-center f-s-30 color-999 " v-if="Number(item.yyysl) >= Number(item.hyzsl)|| (Number(item.hyzsl) - Number(item.yyysl) == '0')">
							<text class="disabled">约满</text>
						</view> -->
						<view v-if="Number(item.yyysl) >= Number(item.hyzsl)|| (Number(item.hyzsl) - Number(item.yyysl) == '0')" class="flex flex-column align-center p-l-12">
							<text class="price"><span class="f-s-24">￥</span>{{item.ghf+item.zcf}}</text>
							<text class="f-s-28 disabled color-999">约满</text>
						</view>
						<view v-else class="flex flex-column align-center p-l-12" @click.stop="showNumberSource(item)">
							<text class="price"><span class="f-s-24">￥</span>{{item.ghf+item.zcf}}</text>
							<text class="reservation f-s-28 color-fff">{{btnText}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="noCard" v-else>
				<view class="images">
					<img src="@/static/images/noCard.png" alt="">
					<view>
						暂未查到排班信息
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 医生详情 -->
		<u-popup :show="showDoctorDetail" :round="10" :safeAreaInsetBottom="true" mode="bottom" @close="close">
			<view class="top-bar flex align-center justify-between p-t-30 p-r-30">
				<text class="f-s-34"></text>
				<img style="width: 34rpx;" src="@/static/images/homeIndex/close-ico.png" @click="close"></img>
			</view>
			<view style="height: 70vh;">
				<scroll-view class="scroll-view_visit" scroll-y="true">
					<view class="flex flex-column align-center" style="padding-top: 0rpx;">
						<u--image width="80" height="80" :src="doctorInfo.doctorImg ? doctorInfo.doctorImg : doctorInfo.sex == '2' ? require('@/static/images/homeIndex/doct-g.png') : doctorInfo.sex == '1' ? require(
									'@/static/images/homeIndex/doct-m.png') : require('@/static/images/homeIndex/avator-doctor.png')"
							shape="circle"></u--image>
						<text class="f-bold color-323232 m-t-30 f-s-36">{{doctorInfo.doctorName}}</text>
						<view class="flex align-center m-t-15">
							<text class="color-333 f-s-30">{{doctorInfo.ghlb}} {{doctorInfo.deptName}}</text>
						</view>
						<view class="m-t-40" style="padding: 0 30rpx;">
							<view class="custom-title flex align-center">
								<view class="dot"></view>
								<text class="f-bold color-323232 f-s-32">医生简介</text>
							</view>
							<view class=" p-l-12 p-r-12 m-t-15">
								<text class="color-666 f-s-30">{{doctorInfo.articleTitle}}</text>
							</view>
						</view>
						<view class="m-t-40" style="padding: 0 30rpx;">
							<view class="custom-title flex align-center">
								<view class="dot"></view>
								<text class="f-bold color-323232 f-s-32">介绍详情</text>
							</view>
							<view class="p-l-12 p-r-12 m-t-15">
								<text class="color-666 f-s-30">{{doctorInfo.articleContent}}</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<!-- 排班详情 -->
		<u-popup :show="showNumTime" :round="10" :safeAreaInsetBottom="true" mode="bottom" @close="closeNumTime">
			<view class="top-bar border-b flex align-center justify-between p-30">
				<text class="f-s-34 ">请选择时间段</text>
				<img style="width: 34rpx;" src="@/static/images/homeIndex/close-ico.png" @click="closeNumTime"></img>
			</view>
			<scroll-view class="scroll-view_visit" scroll-y="true" style="height:70vh;">
				<view class="numberSource">
					<view class="item" v-for="(item,index) in doctorTimeList" :key="index">
						<view class="left">
							{{item.sjdFz}}
						</view>
						<view class="center">
							剩余【{{item.num}}】
						</view>
						<view v-if="judgeIsCanClick(item)" class="right" @click.stop="reservation(item)">
							{{btnText}}
						</view>
						<view v-else class="right" style="background-color: #eee;color: #999;">
							{{btnText}}
						</view>
					</view>
				</view>
			</scroll-view>
		</u-popup>
		<u-modal :show="showModal" title="提示" :content='content' :showCancelButton='true' @confirm='confirmOrder'
			@cancel='cancelOrder'></u-modal>
	</view>
</template>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
	import config from "@/config.js";
	import {
		getDoctorSchedule,
		getScheduTimeAxis,
		getDoctorDetail,
		getScheduInfo,
		getConfigKey
	} from "@/api/home/home.js";
	import {
		reservation,
		checkReservation,
		payUnifiedOrder,
		checkReservationToday
	} from "@/api/pay/index.js";
	import {
		getCurrentDate,
		getTimeStamp,
		nextSevenDay
	} from '@/utils/common.js'
	import {
		encrypt,
		decrypt
	} from '@/utils/sm4Util.js'
	export default {
		data() {
			return {
				showNumTime: false,
				registerType: '2', //1预约  2当天
				id: '',
				dateList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
				showDoctorDetail: false,
				deptCode: '',
				activeIndex: '',
				btnText: '挂号',
				searchDate: '',
				serchName: '',
				doctorList: '',
				doctorInfo: {},
				doctorTimeList: [],
				parms: {},
				content: '',
				obj: {},
				showModal: false,
				gh: '',
				isDirectPay: '1', ////默认挂完号直接支付
			}
		},
		onLoad: function(options) {
			this.getConfig()
			this.deptCode = options.deptCode
			this.gh = options.gh
			this.wardCode = options.wardCode
			this.registerType = options.registerType
			this.serchName = ''
			//registerType 1预约2当班
			if (uni.getStorageSync('hospital') && this.registerType == '1') {
				this.getScheduTimeAxis()
			}
			if (uni.getStorageSync('hospital') && this.registerType == '2') {
				this.searchDate = getCurrentDate()
				this.getSchedulnfo()
			}
		},
		methods: {
			/* 关闭弹窗 */
			close() {
				this.showDoctorDetail = false
			},
			/* 获取参数配置 */
			getConfig() {
				getConfigKey('sys_direct_pay').then(res => {
					this.isDirectPay = res.msg
				});
			},
			confirmOrder() {
				let _that = this
				if (this.registerType == '2') {
					let names = JSON.parse(uni.getStorageSync('currentVisitCard')).name
					let params = {
						cardNum: JSON.parse(uni.getStorageSync('currentVisitCard')).cardNum || '',
						deptCode: this.parms.deptCode || '',
						deptName: this.parms.deptName || '',
						doctorCode: this.parms.doctorCode || '',
						doctorName: this.parms.doctorName || '',
						medicalfee: this.parms.medicalFee || '',
						name: names || '',
						reservfee: this.parms.reservFee || '',
						reservType: '2',
						totalAmount: this.parms.totalAmount || '',
					}
					checkReservationToday(params).then(ress => {
						if (ress.code == 200 && ress.data.orderAmount > 0) {
							/* 挂号 */
							reservation(this.obj).then(res => {
								/* 根据配置判断是否需要支付 */
								if (this.isDirectPay != '1') {
									this.$msg("挂号成功!")
									this.showModal = false
									uni.navigateTo({
										url: '/pages/mine/confirmRegistration/index'
									})
								} else {
									this.showModal = false
									let openid = uni.getStorageSync('openid') || ''
									let obj = {
										"hospitalCode": JSON.parse(uni.getStorageSync('hospital'))
											.hospitalCode, //医院微信唯一标识
										"openId": openid, //微信唯一标识
										"bh": JSON.parse(uni.getStorageSync('currentVisitCard'))
											.cardNum, //住院号/卡号
										"recipelNum": ress.data.cfhList, //处方号（门诊业务专用字段
										"orderAmount": res.data.totalAmount, //订单金额
										"orderDesc": this.btnText == '挂号' ? '当班挂号-' + names : '预约挂号-' +
											names, //订单描述（医卡通，预约，门诊支付 住院押金）
										"payType": "weChat", //支付类型（weChat:微信 Alipay:支付宝）
										"orderType": "3" //订单类型（1医卡通，2预约，3门诊支付 4住院押金）
									}
									let param = {
										params: encrypt(JSON.stringify(obj))
									}
									payUnifiedOrder(param).then(resporns => {
										WeixinJSBridge.invoke('getBrandWCPayRequest', {
												"appId": resporns.data.appId,
												"timeStamp": resporns.data.timeStamp,
												"nonceStr": resporns.data.nonceStr,
												"package": resporns.data.package,
												"signType": "MD5",
												"paySign": resporns.data.paySign,
											},
											function(resporns) { // 调起微信支付成功
												if (resporns.err_msg ==
													"get_brand_wcpay_request:ok") {
													_that.$msg("支付成功!");

												} else if (resporns.err_msg ==
													"get_brand_wcpay_request:cancel") {
													_that.$msg("用户取消支付!");
												} else {
													_that.$msg("支付失败,请重新支付!" + resporns
														.err_msg);
												}
											});
									})
								}
							}).catch(error => {
								this.showModal = false
							})
						}
					}).catch(error => {
						this.showModal = false
					})
				} else {
					reservation(this.obj).then(res => {
						if (res.code == 200) {
							this.$msg("预约成功!")
							this.showModal = false
							uni.navigateTo({
								url: '/pages/mine/confirmRegistration/index'
							})
						}
					}).catch(error => {
						this.showModal = false
					})
				}
			},
			cancelOrder() {
				this.showModal = false
				this.showNumTime = true
			},
			closeNumTime() {
				this.showNumTime = false
			},
			reservation(item) { //挂号保存
				let openid = uni.getStorageSync('openid') || ''
				this.obj = {
					hospitalCode: JSON.parse(uni.getStorageSync('hospital')).hospitalCode,
					openId: openid,
					name: JSON.parse(uni.getStorageSync('currentVisitCard')).name,
					reservType: this.registerType,
					cardNum: JSON.parse(uni.getStorageSync('currentVisitCard')).cardNum,
					orderType: "WeChat",
					orderStatu: '0',
					doctorCode: this.parms.doctorCode,
					doctorName: this.parms.doctorName,
					deptCode: this.parms.deptCode,
					deptName: this.parms.deptName,
					scheduleDate: this.parms.scheduleDate,
					scheduleTime: this.parms.scheduleTime,
					scheduleWeek: this.parms.scheduleWeek,
					scheduleType: this.parms.scheduleType,
					scheduleNum: this.parms.scheduleNum,
					leaveNum: this.parms.leaveNum,
					timeRange: item.sjdFz,
					reservFee: this.parms.reservFee,
					medicalFee: this.parms.medicalFee,
					totalAmount: this.parms.totalAmount,
					scheduleId: item.id,
				}
				let a = this.btnText == '挂号' ? '挂' : '预约'
				this.content = '确认要' + a + this.parms.doctorName + '医生:' + item.sjdFz +
					'的号？'
				this.showModal = true
				this.showNumTime = false
			},
			showNumberSource(item) {
				if (!uni.getStorageSync('currentVisitCard')) {
					this.$modal.msgError("请先绑定就诊人");
					uni.navigateTo({
						url: '/pages/addHealthCard/index?jumpType=2'
					})
					return
				}
				this.parms = {
					reservFee: item.ghf,
					doctorCode: item.gh,
					doctorName: item.xm,
					deptCode: item.dept_code,
					deptName: item.dept_name,
					scheduleTime: item.banci,
					scheduleWeek: item.week,
					scheduleType: item.ghlb,
					scheduleNum: item.hyzsl,
					leaveNum: item.hyzsl - item.yyysl,
					medicalFee: item.zcf,
					scheduleDate: item.pbrq,
					totalAmount: item.ghf + item.zcf,
				}
				let obj = {
					hospitalCode: JSON.parse(uni.getStorageSync('hospital')).hospitalCode,
					deptCode: this.deptCode,
					doctorCode: item.gh,
					doctorScheduleid: item.id
				}
				getScheduInfo(obj).then(res => {
					this.doctorTimeList = res.data
					this.showNumTime = true
				})

			},
			/* 校验挂号按钮是否可点击 */
			judgeIsCanClick(item) {
				if (getCurrentDate() == this.searchDate) {
					let endTime = item.sjdFz
					let index = endTime.lastIndexOf("\~");
					let str = endTime.substring(index + 1, endTime.length);
					let newDate = new Date().getTime()
					let endDate = new Date(getTimeStamp(new Date()) + ' ' + str +
						':00').getTime()
					if (newDate > endDate) {
						return false
					} else {
						return true
					}
				} else {
					return true
				}
			},
			showDetail(item) {
				getDoctorDetail(item.doctor_id).then(res => {
					this.doctorInfo = res.data;
					if(this.doctorInfo.doctorImg){
						let imgurl = this.doctorInfo.doctorImg;
						let index = imgurl.indexOf('/profile');
						let urlParts = imgurl.slice(index);
						this.doctorInfo.doctorImg = config.baseUrl + urlParts;
					}
					this.showDoctorDetail = true
				})
			},
			viewDoctr(item, index) { //切换上边日期
				if (item.isReservation == 1) {
					this.activeIndex = index
					if (new Date(item.reservationTime).getDate() != new Date().getDate()) {
						this.btnText = '预约'
					} else {
						this.btnText = '挂号'
					}
					this.searchDate = item.reservationTime
					this.serchName = item.serchName
					this.getSchedulnfo()
				}
			},
			getScheduTimeAxis() { //排版时间轴
				let obj = {
					hospitalCode: JSON.parse(uni.getStorageSync('hospital')).hospitalCode,
					deptCode: this.deptCode ? this.deptCode : '45',
					startDate: nextSevenDay()[0].date,
					endDate: nextSevenDay()[6].date,
				}
				getScheduTimeAxis(obj).then(res => {
					res.data.map((item, index) => {
						if (new Date(item.reservationTime).getDate() == new Date().getDate()) {
							item.day = '今天'
						} else {
							item.day = new Date(item.reservationTime).getDate() + '日'
						}

					})
					let indexs = res.data.findIndex(item => item.isReservation == '1')
					this.dateList = res.data.map(item => {
						item.reservationWeek == 1 ? item.reservationWeek = "一" : "";
						item.reservationWeek == 2 ? item.reservationWeek = "二" : "";
						item.reservationWeek == 3 ? item.reservationWeek = "三" : "";
						item.reservationWeek == 4 ? item.reservationWeek = "四" : "";
						item.reservationWeek == 5 ? item.reservationWeek = "五" : "";
						item.reservationWeek == 6 ? item.reservationWeek = "六" : "";
						item.reservationWeek == 7 ? item.reservationWeek = "日" : "";
						return item
					})
					this.activeIndex = indexs
					this.searchDate = res.data[indexs].reservationTime
					this.getSchedulnfo()
				})
			},
			/* 打开弹窗 */
			open() {
				this.showDoctorDetail = true
			},
			/* 获取排班信息 */
			getSchedulnfo() { //获取医生
				let obj = {
					hospitalCode: JSON.parse(uni.getStorageSync('hospital')).hospitalCode,
					deptCode: this.deptCode,
					wardCode: this.wardCode,
					searchDate: this.searchDate,
					serchName: this.serchName,
					gh: this.gh
				}
				getDoctorSchedule(obj).then(res => {
					this.doctorList = res.data
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	page {
		height: 100%;

		// .border-b{
		// 	border-bottom: 1px solid #F6F7F9;
		// }
		.price {
			color: #FF6430;
			font-size: 32rpx;
			margin-bottom: 10rpx;
		}
		.disabled{
			background-color: #f1f1f1;
			 padding: 6rpx 24rpx;
			 border-radius: 10rpx;
		}
		.noCard {
			width: 100%;
			text-align: center;
			color: #666666;
			margin-top: 64rpx;

			.images {
				width: 100%;
				margin-bottom: 20px;
				color: #666666;

				img {
					width: 55%;
					text-align: center;
				}
			}

		}

		.numberSource {
			font-size: 30rpx;
			padding: 0 20rpx;
			border-top: 1px solid #eee;

			.item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 24rpx;
				border-bottom: 1px solid #eee;

				.right {
					background-color: #4D8EFF;
					padding: 6rpx 24rpx;
					border-radius: 10rpx;
					color: #fff;
					font-size: 28rpx;
				}
			}
		}

		.text2hang {
			-webkit-line-clamp: 2;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			overflow: hidden;
		}

		.doctor-container {
			width: 100%;
			height: 100%;
			background-color: #F6F7F9;

			.scroll-view_visit {
				width: 100%;
				height: 100%;

				.custom-title {
					.dot {
						width: 10rpx;
						height: 32rpx;
						border-radius: 10rpx;
						background-color: #4D8EFF;
						margin-right: 10rpx;
					}
				}

				.avatar {
					width: 160rpx;
					border-radius: 100%;
				}

			}


			.scroll-view_H {
				width: 100%;
				height: 100%;

				.top {
					width: 100%;
					background-color: #fff;

					.date-item {
						height: 140rpx;
						padding: 10rpx 0;

						.week {
							color: #999;
							font-size: 28rpx;
						}

						.day {
							color: #333;
							font-size: 32rpx;
						}

						.hao {
							color: #999;
							font-size: 28rpx;
						}
					}

					.avtive {
						background: #E7F1FF;
						color: #4D8EFF;

						.week {
							color: #4D8EFF;
						}

						.day {
							color: #4D8EFF;
						}

						.hao {
							color: #4D8EFF;
						}
					}

					.alldoctor {
						width: 100rpx;
						height: 140rpx;
						// background: rgba(77, 142, 255, 0.3);
						border-right: 1rpx solid #F6F7F9;
					}
				}


				.registra-date {
					padding: 24rpx;

					.item {
						margin-bottom: 24rpx;

						.item-bot {
							width: 100%;
							padding: 30rpx 24rpx;
							background-color: #fff;
							border-radius: 12rpx;

							.reservation {
								background-color: #4D8EFF;
								padding: 6rpx 24rpx;
								border-radius: 10rpx;
							}

							.avatar {
								width: 110rpx;
								height: 110rpx;
								border-radius: 100%;
							}
						}


					}
				}




			}

		}

	}
</style>